package com.dy.lock.screen.api.server;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

import com.dy.lock.screen.api.parse.BeanVO;
import com.dy.lock.screen.api.parse.Parser;
import com.dy.lock.screen.api.utils.SMSUtil;

public class HttpServerStartMain {

	private static Logger log = Logger.getLogger(HttpServerStartMain.class);

	private static final ReentrantLock lock = new ReentrantLock();

	public static void main(String[] args) throws Exception {
		Server server = new Server();
		ServletContextHandler context = new ServletContextHandler(
				ServletContextHandler.SESSIONS);
		SelectChannelConnector selectchannelconnector = new SelectChannelConnector();
		selectchannelconnector.setPort(Integer.parseInt(HttpServerStartMain
				.getValue("server.http.port")));

		// 线程池队列线程数
		String threadNumStr = HttpServerStartMain
				.getValue("server.http.threadPool");
		int threadNum = Integer.parseInt(threadNumStr);
		if (threadNumStr != null && !("".equals(threadNumStr)) && threadNum > 0) {
			selectchannelconnector
					.setThreadPool(new QueuedThreadPool(threadNum)); // 配置文件中读取的值
		} else {
			selectchannelconnector.setThreadPool(new QueuedThreadPool(20)); // 默认值
		}
		selectchannelconnector.setMaxIdleTime(30000);
		selectchannelconnector.setName("test");
		selectchannelconnector.setRequestHeaderSize(8192);
		server.setConnectors(new Connector[] { selectchannelconnector });
		context.setContextPath(HttpServerStartMain
				.getValue("server.http.context.path"));
		server.setHandler(context);

		List<BeanVO> beanList = new Parser().getBeanList();
		for (BeanVO bean : beanList) {
			context.addServlet(bean.getClasses(), bean.getUrlPattern());
		}
		// 注册短信接口服务,不能频繁调用
//		SMSUtil.regist();
		server.start();
		log.info("系统启动，访问路径:" + context.getContextPath() + "开放端口:"
				+ selectchannelconnector.getPort());
		server.join();
	}

	public static String getValue(String key) {
		if (prop == null)
			readProp();
		return prop.getProperty(key);
	}

	private static Properties prop = null;

	private static void readProp() {
		if (prop == null) {
			try {
				lock.lock();
				if (prop == null) {
					Properties pro = new Properties();
					try {
						pro.load(HttpServerStartMain.class.getClassLoader()
								.getResourceAsStream("com.properties"));
					} catch (IOException e) {
						// TODO Auto-generated catch block
					}
					if (!pro.isEmpty())
						prop = pro;
				}
			} finally {
				lock.unlock();
			}
		}
	}
}